package com.photoeditor.demo.ui.widget.image;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.gpuimage.GPUImageFilter;
import com.android.gpuimage.IDynamicFilter;
import com.common.base.utils.thread.ThreadPool;
import com.photoeditor.R;
import com.photoeditor.demo.app.ItemClickSupport;
import com.photoeditor.demo.db.DataManager;
import com.photoeditor.demo.db.FilterBean;
import com.photoeditor.demo.db.FilterCategoryBean;
import com.photoeditor.demo.db.FilterConstant;
import com.photoeditor.demo.model.event.RefreshFilterCategory;
import com.photoeditor.demo.model.event.SortFilterCategory;
import com.photoeditor.demo.model.filter.ImageFilterTools;
import com.photoeditor.demo.model.filter.RandomListGenerater;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpConstant;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.store.download.DownloadUtils;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.model.store.module.StoreOnlineManager;
import com.photoeditor.demo.ui.activity.edit.EditorImageActivity;
import com.photoeditor.demo.ui.activity.edit.MediaEditBaseActivity;
import com.photoeditor.demo.ui.widget.BottomInsideBarView;
import com.photoeditor.demo.ui.widget.CircleTextProgressbar;
import com.photoeditor.demo.ui.widget.HRecyclerView;
import com.photoeditor.demo.ui.widget.MultiToggleImageButton;
import com.photoeditor.demo.ui.widget.animator.ScatterAnimator;
import com.photoeditor.demo.util.PluginVersionUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.photoeditor.demo.statistics.StatisticsConstant.SOURCE_TYPE_COLLAGE;
import static com.photoeditor.demo.statistics.StatisticsConstant.SOURCE_TYPE_EDIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.SOURCE_TYPE_IMAGE_STASH;
import static com.photoeditor.demo.statistics.StatisticsConstant.SOURCE_TYPE_VIDEO_STASH;

/**
 * 编辑界面滤镜修改
 */
public class FilterBarView extends LinearLayout implements IOnProgressChange, View.OnClickListener {

    private static final int VIGNETTE_MODE_OFF = 0;
    private static final int VIGNETTE_MODE_ON = 1;
    private static final int TILTSHIFT_MODE_OFF = 0;
    private static final int TILTSHIFT_MODE_RADIAL = 1;
    private static final int TILTSHIFT_MODE_LINEAR = 2;

    private final int TYPE_NORMAL = 0;
    private final int TYPE_ARTISTIC = 1;
    private int mType = TYPE_NORMAL;

    HRecyclerView mFilterCategoryListView;
    HRecyclerView mFilterListView;
    MultiToggleImageButton mVignetteBtn;
    MultiToggleImageButton mTiltshift;

    /**
     * 主要用于随机滤镜功能，滤镜更新删除时需要更新
     **/
    private ArrayList<FilterBean> mAllFilterBean;
    /**
     * 由于现在所有的滤镜在下载（可用）之前都已经显示了，没下载的并不能应用，所以需要用一个新变量取代
     **/
    private ArrayList<FilterBean> mAllDownloadedBeans;
    private FilterRecylerAdapter mFilterAdapter = null;
    private FilterCategoryAdapter mFilterCategoryAdapter = null;
    public FilterBean mCurrentFilterBean = null;

    private String mCurrentFilterName = ImageFilterTools.FILTER_NAME_DEFAULT;

    private MediaEditBaseActivity mActivity;

    private GPUImageFilter mCurrentFilter;

    private GPUImageFilter mDefaultFilter;

    private boolean mFinishInflate = false;
    private Bitmap mBaseBitmap;
    private int mFilterType = FilterAdapter.Edit_FILTER_TYPE;

    private ScatterAnimator mFilterListAnimator;
    private boolean mFilterCategoryAnimationing = false;
    private RefreshFilterCategory mPendingRefreshFilterCategoryEvent = null;
    private SortFilterCategory mPendingSortFilterCategoryEvent = null;
    private String mCurrentPressedFilterCategory = null;
    private static final int FILTER_CATEGORY_ANIMATION_DURING = 100;
    private static final int FILTER_ANIMATION_DURING = 220;

    private RandomListGenerater mRandomListGenerater;
    private OnFilterSwitchListener mOnFilterSwitchListener;

    private ItemClickSupport mItemClickSupport;

    private RelativeLayout mDownloadLayout;
    private CircleTextProgressbar mDownloadProgressbar;
    private ImageView mDonwloadIcon;

    private RecyclerView.LayoutManager mFilterListLayoutManager;
    private boolean mNeedScroll = true;
    private boolean mFromCategoryClick = false;
    private int mCheck2ApplyPosition;

    public FilterBarView(Context context) {
        this(context, null);
    }

    public FilterBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (attrs != null) {
            TypedArray typed = getContext().obtainStyledAttributes(attrs, R.styleable.FilterBarView);
            mFilterType = typed.getInt(R.styleable.FilterBarView_filter_type, FilterAdapter.Edit_FILTER_TYPE);
        }
        mActivity = (MediaEditBaseActivity) context;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        init();
        mFinishInflate = true;
    }

    private void bindView() {
        mFilterCategoryListView = (HRecyclerView) findViewById(R.id.filter_category_list);
        mFilterListView = (HRecyclerView) findViewById(R.id.filter_listview);
        mVignetteBtn = (MultiToggleImageButton) findViewById(R.id.vignette_button);
        mTiltshift = (MultiToggleImageButton) findViewById(R.id.tiltshift_button);
        mDownloadLayout = findViewById(R.id.rly_download);
        mDownloadProgressbar = findViewById(R.id.progress_view);
        mDonwloadIcon = findViewById(R.id.iv_download_icon);
        mVignetteBtn.setOnClickListener(this);
        mTiltshift.setOnClickListener(this);
        mDonwloadIcon.setOnClickListener(this);
    }

    public void init() {
        mDefaultFilter = new GPUImageFilter();
        bindView();
        initView();
        if (mBaseBitmap != null) {
            mFilterAdapter.setBaseBitmap(mBaseBitmap);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.vignette_button:
                onVignetteBtnClicked();
                break;
            case R.id.tiltshift_button:
                onTiltShiftBtnClicked();
                break;
            case R.id.iv_download_icon:
//                downloadFilter();
                break;
        }
    }

    private void downloadFilter(FilterBean lfb) {
        DownloadUtils.getInstance().startDownload(StoreOnlineManager.getInstance().getFilterItemBeanByPackageName(lfb.getPackageName()), BaseOnlineManager.STORE_FUNC_TYPE_FILTER);
    }

    void onVignetteBtnClicked() {
    }

    void onTiltShiftBtnClicked() {
    }

    /**
     * 初始化滤镜分类数据
     */
    private void initFilterCategoryListView() {
        mAllFilterBean = DataManager.getInstance().getLocalFilterListStatusUseByOrder();
        getDownloadedFilters();
        mFilterCategoryAdapter = new FilterCategoryAdapter();
        mFilterCategoryAdapter.setData(DataManager.getInstance().loadAllFilterCategory());
        mFilterCategoryListView.setAdapter(mFilterCategoryAdapter);
        mItemClickSupport = new ItemClickSupport(mFilterCategoryListView, mFilterCategoryAdapter);
        mFilterCategoryAdapter.setItemClickSupport(mItemClickSupport);
        mItemClickSupport.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {

            /**
             * 滤镜分类点击事件
             */
            @Override
            public void onItemClick(RecyclerView recyclerView, View view, int position, long id) {
                //商店所有的滤镜都展示在这里，没有商店了
                // 跳转滤镜二级分类页面
                if (mFilterCategoryAdapter.getData() == null || position < 0 || position >= mFilterCategoryAdapter.getData().size()) {
                    return;
                }
                FilterCategoryBean category = mFilterCategoryAdapter.getData().get(position);
                showFilterSecondCategoryList(category.getCategoryId(), position, view);

                // TODO: 2019/7/8 点击标签后底部列表滑动到指定位置
                List<FilterBean> data = mFilterAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    if (position == data.get(i).getCategoryPosition()) {
                        scollToPosition(i, mFilterListView);
                        break;
                    }
                }

                mCurrentPressedFilterCategory = category.getCategoryId();
                mFilterCategoryAdapter.setSelItemIndex(position, view);
                mFilterCategoryAdapter.notifyDataSetChanged();
                /*//这里要判断下滤镜是否已安装，已经安装了的不展示下载按钮
                boolean exist = DataManager.getInstance().isExistFilterForFilterCategory(category.getCategoryId());
                mDownloadLayout.setVisibility(exist?View.GONE:View.VISIBLE);
                if (!exist) {
                    mDownloadProgressbar.setProgress(0);
                    mDonwloadIcon.setVisibility(View.VISIBLE);
                }
                if (mCurrBean != null) {
                    if (mIDownloadListener != null) {
                        DownloadUtils.getInstance().removeListener(mIDownloadListener);
                    }
                    mIDownloadListener = new DownloadListener(mCurrBean.getCategoryId(), FilterBarView.this);
                    DownloadUtils.getInstance().addListener(mIDownloadListener);
                }*/
            }
        });
        initFilterListView();
    }

    private void getDownloadedFilters() {
        if (mAllDownloadedBeans == null) {
            mAllDownloadedBeans = new ArrayList<>();
        } else {
            mAllDownloadedBeans.clear();
        }
        if (mAllFilterBean == null) {
            return;
        }
        for (FilterBean bean : mAllFilterBean) {
            if (!TextUtils.isEmpty(bean.getApkUri())) {
                mAllDownloadedBeans.add(bean);
            }
        }
    }

    private boolean isFromStash() {
        return mSourceType == SOURCE_TYPE_IMAGE_STASH || mSourceType == SOURCE_TYPE_VIDEO_STASH;
    }

    private int mSourceType = SOURCE_TYPE_EDIT;

    public void setSourceType(int type) {
        mSourceType = type;
        if (mSourceType == SOURCE_TYPE_EDIT || mSourceType == SOURCE_TYPE_COLLAGE) {
            if (mFilterCategoryAdapter != null) {
                mFilterCategoryAdapter.setSelectEffectType(FilterCategoryAdapter.SELECT_EFFECT_BG);
                mFilterCategoryAdapter.notifyDataSetChanged();
            }
            if (mFilterAdapter != null) {
                mFilterAdapter.setSelectEffectType(FilterCategoryAdapter.SELECT_EFFECT_BG);
                mFilterAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 显示滤镜二级分类
     */
    private void showFilterSecondCategoryList(final String categoryId, final int clickPosition, View clickView) {
//        updateFilterAdapter(categoryId);
    }

    private void initFilterListView() {
        mFilterAdapter = new FilterRecylerAdapter(mActivity, /*mFilterType*/FilterRecylerAdapter.MAIN_FILTER_TYPE);
        mFilterAdapter.setData(new ArrayList<FilterBean>());
        mFilterListView.setAdapter(mFilterAdapter);
        mFilterListAnimator = new ScatterAnimator(mFilterListView);
        mFilterListAnimator.setAddDuration(FILTER_ANIMATION_DURING);
        mFilterListAnimator.setRemoveDuration(FILTER_ANIMATION_DURING);
        mFilterListView.setItemAnimator(mFilterListAnimator);
        ItemClickSupport itemClickSupport = new ItemClickSupport(mFilterListView, mFilterAdapter);
        mFilterAdapter.setItemClickSupport(itemClickSupport);
        itemClickSupport.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View view, int position, long id) {
                //点击的滤镜item
                if (mFilterAdapter.getData() == null || position == mFilterAdapter.getSeletcItemPosition() || position >= mFilterAdapter.getData().size()) {
                    return;
                } else {
                    if (position < 0 || position >= mFilterAdapter.getData().size()) {
                        return;
                    }
                    FilterBean lfb = mFilterAdapter.getData().get(position);
                    if (lfb.getType() == FilterConstant.TYPE_DOWNLOAD || lfb.getType() == FilterConstant.TYPE_ARTISTIC) {
                        File f = new File(lfb.getApkUri());
                        if (!f.exists()) {
                            mCheck2ApplyPosition = position;
                            downloadFilter(lfb);
                            return;
                        }
                    }
                    mCheck2ApplyPosition = -1;
                    if (switchFilter(lfb)) {
                        mFilterAdapter.setSeletcItemPosition(position, view, recyclerView);
//                        mFilterAdapter.notifyDataSetChanged();

                        if (mActivity instanceof EditorImageActivity) {
//                            ((ImageEditActivity) mActivity).setUsedBuyFilter(lfb.isBuy());
                        }
                    }
                }
            }
        });

        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (mFilterListView != null && mFilterListView.getVisibility() == View.VISIBLE && mFilterCategoryAdapter.getData() != null && !mFilterCategoryAdapter.getData().isEmpty()) {
                    updateFilterAdapter();
                }
            }
        }, 100);

        mFilterListLayoutManager = mFilterListView.getLayoutManager();
        mFilterListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // TODO: 2019/7/8 控制两个列表交互
                if (mNeedScroll && mFilterListLayoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager gridLayoutManager = (LinearLayoutManager) mFilterListLayoutManager;
                    //获取第一个可见view的位置
                    int firstVisibleItemPosition = gridLayoutManager.findFirstVisibleItemPosition();
                    try {
                        int categoryPosition = mFilterAdapter.getData().get(firstVisibleItemPosition).getCategoryPosition();
                        mFilterCategoryListView.smoothScrollToPosition(categoryPosition);
                        mFilterCategoryAdapter.setSelItemIndex(categoryPosition, null);
                        mFilterCategoryAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mFromCategoryClick && newState == RecyclerView.SCREEN_STATE_OFF) {
                    mFromCategoryClick = false;
                    mNeedScroll = true;
                }
            }

        });
    }

    private void updateFilterAdapter() {
//            ArrayList<FilterBean> list = ImageFilterTools.getFilterData(getContext(), categoryId);
        mFilterAdapter.setData(DataManager.getInstance().loadAllFilter(isFromStash()));
        if (mCurrentFilterBean != null) {
            int position = mFilterAdapter.getPositionByFilterPkgName(mCurrentFilterBean.getPackageName());
            mFilterAdapter.setSeletcItemPosition(position);
//            mFilterListView.setSelection(position);
        } else {
            mFilterAdapter.setSeletcItemPosition(0);
//            mFilterListView.setSelection(0);
        }
        mFilterAdapter.notifyDataSetChanged();

    }

    public void initView() {
        getChildAt(0).setBackgroundColor(Color.TRANSPARENT);
        mVignetteBtn.overrideImageIds(new int[]{
                R.drawable.icon_lucency_vignette_off,
                R.drawable.icon_lucency_vignette_on
        });
        mVignetteBtn.setState(VIGNETTE_MODE_OFF);
        mTiltshift.overrideImageIds(new int[]{
                R.drawable.icon_lucency_blur_off,
                R.drawable.icon_lucency_blur_on,
                R.drawable.icon_lucency_blur_line
        });
        initFilterCategoryListView();
    }

    private void onClickRandomFilter() {
//        if (mFilterCategoryAnimationing) {
//            return;
//        }
        int dx;
        dx = 1;
        int max = mAllDownloadedBeans.size() - dx;
        if (mAllDownloadedBeans.size() <= 0) {
            showGotoFilterStoreDilog();
        } else {
            if (mRandomListGenerater == null) {
                mRandomListGenerater = new RandomListGenerater();
            }
            int random = mRandomListGenerater.next(max);
            FilterBean lfb = mAllDownloadedBeans.get(random);
            if (mCurrentFilterBean != null
                    && lfb.getPackageName().equals(mCurrentFilterBean.getPackageName())) {
                random = mRandomListGenerater.next(max);
            }

            /**
             * 滤镜文件不存在
             */
            lfb = mAllDownloadedBeans.get(random);
            if (lfb.getType() == FilterConstant.TYPE_DOWNLOAD) {
                File f = new File(lfb.getApkUri());
                if (!f.exists()) {

                    return;
                } else {
                    mDownloadLayout.setVisibility(View.GONE);
                }
            }

            boolean result = switchFilter(lfb);
            if (result) {
                int selPosition = mFilterCategoryAdapter.getPositionByCategoryId(mCurrentFilterBean.getCategoryId());
                mFilterCategoryListView.setSelection(selPosition);
                mFilterCategoryAdapter.notifyDataSetChanged();

                List<FilterBean> filters = DataManager.getInstance().loadAllFilter(isFromStash());
                mFilterAdapter.setData(filters);

                int selPosition2 = -1;
                for (FilterBean bean : filters) {
                    selPosition2++;
                    if (mCurrentFilterBean.getPackageName().equals(bean.getPackageName())) {
                        break;
                    }
                }
                if (selPosition2 != -1) {
                    mFilterAdapter.setSeletcItemPosition(selPosition2);
                    mFilterAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void showGotoFilterStoreDilog() {
        if (mRandomListGenerater == null) {
            mRandomListGenerater = new RandomListGenerater();
        }
        List<FilterCategoryBean> list = mFilterCategoryAdapter.getData();
        if (list != null && !list.isEmpty()) {
            int max = list.size();
            int random = mRandomListGenerater.next(max);

            mFilterCategoryAdapter.setSelItemIndex(random, null);
            mFilterCategoryListView.setSelection(random);
            mFilterCategoryAdapter.notifyDataSetChanged();

            List<FilterBean> filters = DataManager.getInstance().loadAllFilter(isFromStash());
            mFilterAdapter.setData(filters);
        }
//        new AlertDialog.Builder(mActivity)
//                .setTitle(R.string.tip)
//                .setMessage(R.string.go_to_filter_store_tips)
//                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                })
//                .setPositiveButton(R.string.go_to_filter_store, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        Intent i = new Intent(getContext(), StoreActivity.class);
//                        getContext().startActivity(i);
//                        ((Activity)getContext()).overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_no_animation);
//                    }
//                }).show();
    }

    public void hidevignetteTiltshiftButton() {
        findViewById(R.id.left_icon).setVisibility(View.GONE);
    }

    /**
     * 切换滤镜
     * 艺术滤镜和普通滤镜实现不一样，在这里分开处理
     *
     * @param bean
     */
    public boolean switchFilter(FilterBean bean) {
        if (bean != null) {
            if (!checkApplyalbe(bean)) {
                return false;
            }
            if (bean.getType() != FilterConstant.TYPE_ORIGINAL && TextUtils.isEmpty(bean.getApkUri())) {
                return false;
            }
            mFilterCategoryAdapter.setSelItemIndex(bean.getCategoryPosition(), null);
        }
        mCurrentFilterBean = bean;
        if (mCurrentFilterBean == null) {
            mCurrentFilterName = ImageFilterTools.FILTER_NAME_DEFAULT;
        } else {
            mCurrentFilterName = mCurrentFilterBean.getName();
        }
        mFilterCategoryAdapter.notifyDataSetChanged();
        updateFilterCategoryData(bean);
        if (mCurrentFilter != null) {
            ImageFilterTools.resetFilterIntensity(mCurrentFilter);
        }
        if (mCurrentFilterBean != null && mCurrentFilterBean.getType() == FilterConstant.TYPE_ARTISTIC) {
            //艺术滤镜
            mType = TYPE_ARTISTIC;
            GPUImageFilter filter = ImageFilterTools.createFilterForType(mActivity, mCurrentFilterBean);
            if (filter != null) {
                mCurrentFilter = filter;
                setFilterUpdateOn(filter);
                mActivity.setFilter(filter);
                EditorImageActivity imageEditActivity = null;
                if (mActivity instanceof EditorImageActivity) {
                    imageEditActivity = (EditorImageActivity) mActivity;
                }
                if (mCurrentFilterBean != null && mCurrentFilter.isSupportIntensity()) {
                    if (imageEditActivity != null && imageEditActivity.isNeedGoToBeauty()) {
                        imageEditActivity.hideTopView();
                        imageEditActivity.showOperationBarWithAnim(R.id.filter, (int) (ImageFilterTools.getFilterIntensity(filter) * 100),
                                mCurrentFilterBean.getColor());
                    } else {
                        mActivity.showInsideBottomBarWithProgress((int) (ImageFilterTools.getFilterIntensity(filter) * 100),
                                mCurrentFilterBean.getColor());
                    }
                } else {
                    if (imageEditActivity != null && imageEditActivity.isNeedGoToBeauty()) {
                        imageEditActivity.hideTopView();
                        imageEditActivity.showOperationBarWithAnim(R.id.filter, mCurrentFilterName);
                    } else {
                        mActivity.showInsideBottomBarWithName(mCurrentFilterName);
                    }
                }
                mActivity.setConfirmEnable(true);
            } else {
                mActivity.showInsideBottomBarWithName(mCurrentFilterName);
            }
            if (mOnFilterSwitchListener != null) {
                mOnFilterSwitchListener.onSwitch(mCurrentFilterBean);
            }
            return true;
        } else {
            //普通滤镜
            mType = TYPE_NORMAL;
            GPUImageFilter filter = ImageFilterTools.createFilterForType(mActivity, mCurrentFilterBean);
            if (filter != null) {
                mCurrentFilter = filter;
                setFilterUpdateOn(filter);
                mActivity.setFilter(filter);
                EditorImageActivity imageEditActivity = null;
                if (mActivity instanceof EditorImageActivity) {
                    imageEditActivity = (EditorImageActivity) mActivity;
                }
                if (mCurrentFilterBean != null && mCurrentFilter.isSupportIntensity()) {
                    if (imageEditActivity != null && imageEditActivity.isNeedGoToBeauty()) {
                        imageEditActivity.hideTopView();
                        imageEditActivity.showOperationBarWithAnim(R.id.filter, (int) (ImageFilterTools.getFilterIntensity(filter) * 100),
                                mCurrentFilterBean.getColor());
                    } else {
                        mActivity.showInsideBottomBarWithProgress((int) (ImageFilterTools.getFilterIntensity(filter) * 100),
                                mCurrentFilterBean.getColor());
                    }
                } else {
                    if (imageEditActivity != null && imageEditActivity.isNeedGoToBeauty()) {
                        imageEditActivity.hideTopView();
                        imageEditActivity.showOperationBarWithAnim(R.id.filter, mCurrentFilterName);
                    } else {
                        mActivity.showInsideBottomBarWithName(mCurrentFilterName);
                    }
                }
                mActivity.setConfirmEnable(true);
            } else {
                mActivity.showInsideBottomBarWithName(mCurrentFilterName);
            }
            if (mOnFilterSwitchListener != null) {
                mOnFilterSwitchListener.onSwitch(mCurrentFilterBean);
            }
            return true;
        }
    }

    private void updateFilterCategoryData(FilterBean selBean) {
        if (selBean == null
                || mFilterCategoryAdapter == null
                || mFilterCategoryAdapter.getData() == null
                || mFilterCategoryAdapter.getData().size() == 0) {
            return;
        }
        for (FilterCategoryBean categoryBean : mFilterCategoryAdapter.getData()) {
            if (categoryBean.getCategoryId() != null
                    && categoryBean.getCategoryId().equals(selBean.getCategoryId())) {
                categoryBean.setIconUrl(selBean.getIcon());
                if (categoryBean.getType() == FilterConstant.TYPE_DOWNLOAD) {
                    categoryBean.setSelFilterBean(selBean);
                } /*else {
                    if (!TextUtils.isEmpty(categoryBean.getFirstFilterId())) {
                        categoryBean.setSelFilterBean(DataManager.getInstance().getLocalFilterByPackageName(categoryBean.getFirstFilterId()));
                    } else {
                        categoryBean.setSelFilterBean(null);
                    }
                    Object res = ImageFilterTools.BUILDIN_FILTER_ICON_RESID.get(selBean.getPackageName());
                    if (res instanceof Integer) {
                        categoryBean.setIconResId((Integer) res);
                    }
                }*/
                mFilterCategoryAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 重制View
     */
    public void reset() {
        mCheck2ApplyPosition = -1;
        if (mFilterCategoryAdapter != null) {
            mFilterCategoryAdapter.setSelItemIndex(0, null);
            mFilterCategoryAdapter.notifyDataSetChanged();
            mFilterCategoryListView.setSelection(0);
        }
        if (mFilterAdapter != null) {//让滤镜恢复到第一个
            mCurrentFilterBean = null;
            mFilterAdapter.setSeletcItemPosition(0);
            mFilterAdapter.notifyDataSetChanged();
            mFilterListView.setSelection(0);
        }
        mActivity.setFilter(mDefaultFilter);
    }

    /**
     * 获取上次的Filter的名称
     *
     * @return
     */
    public String getCurrentFilterName() {
        if (mCurrentFilterBean != null) {
            return mCurrentFilterBean.getName();
        } else {
            return ImageFilterTools.FILTER_NAME_DEFAULT;
        }
    }

    public String getCurrentFilterName2() {
        return mCurrentFilterName;
    }

    public String getCurrentFilterPkgName() {
        if (mCurrentFilterBean != null) {
            return mCurrentFilterBean.getPackageName();
        } else {
            return "";
        }
    }

    public FilterBean getCurrentFilterBean() {
        return mCurrentFilterBean;
    }

    public boolean isArtisticFilter() {
        return mType == TYPE_ARTISTIC;
    }

    public FilterCategoryBean getCurrentFilterCategoryBean() {
        if (mCurrentFilterBean != null) {
            String categoryId = mCurrentFilterBean.getCategoryId();
            FilterCategoryBean filterCategoryBeanByCategoryId = mFilterCategoryAdapter.getFilterCategoryBeanByCategoryId(categoryId);
            return filterCategoryBeanByCategoryId;
        }
        return null;
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (!mSaveStatus && visibility == View.VISIBLE && mActivity != null) {
            mActivity.setFilter(mDefaultFilter);
        }
    }

    private boolean mSaveStatus = false;

    public void setSaveStatus(boolean saveStatus) {
        mSaveStatus = saveStatus;
    }

    /**
     * 处理Touch
     *
     * @param v
     * @param event
     */
    public void dealOnTouch(View v, MotionEvent event) {
        if (mCurrentFilterBean != null) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mActivity.setFilter(mDefaultFilter);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (mCurrentFilter != null) {
                    mActivity.setFilter(mCurrentFilter);
                }
            }
        }
    }

    public void dealOnLongTouch() {
        if (mCurrentFilterBean != null) {
            mActivity.clearFilter(mDefaultFilter);
        }
    }

    public void dealCancleLongTouch() {
        if (mCurrentFilterBean != null) {
            mActivity.setFilter(mCurrentFilter);
        }
    }

    /**
     * 获取当前的Filter的新实例
     *
     * @return
     */
    public GPUImageFilter newCurrentFilter() {
        GPUImageFilter filter = null;
        if (mCurrentFilterBean != null) {
            filter = ImageFilterTools.createFilterForType(mActivity, mCurrentFilterBean);
        } else {
            FilterBean filterBean = new FilterBean();
            filterBean.setType(FilterConstant.TYPE_ORIGINAL);
            filter = ImageFilterTools.createFilterForType(mActivity, filterBean);
        }
        setFilterUpdateOn(filter);
        ImageFilterTools.setFilterIntensity(filter, mActivity.getSeekBarProgress() / 100f);
        return filter;
    }

    @Override
    public void onProgressChange(int progress) {
        switch (mType) {
            case TYPE_NORMAL:
                if (mCurrentFilter != null) {
                    ImageFilterTools.setFilterIntensity(mCurrentFilter, progress / 100f);
                    mActivity.requestRender();
                }
                break;
            case TYPE_ARTISTIC:
                mActivity.requestDraw(progress / 100f);
                break;
        }

    }

    /**
     * @param bitmap 注意这里考虑了View是否初始化  如果没有初始化则缓存住图片  初始化之后会设置到mFilterAdapter
     *               如果已经初始化则直接设置进去
     */
    public void setBaseBitmap(Bitmap bitmap) {
//        mBaseBitmap = bitmap;
//        if (mFinishInflate) {
//            mFilterAdapter.setBaseBitmap(bitmap);
//        }
    }

    public Bitmap getBaseBitmap() {
        return mBaseBitmap;
    }

    /**
     * 回收资源
     */
    public void onDestory() {
        if (mFilterAdapter != null) {
            mFilterAdapter.onDestory();
        }
        /*if (mFilterCategoryAdapter != null && mFilterCategoryAdapter.getData() != null && mFilterCategoryAdapter.getData().size() > 0) {
            DownloadUtils.getInstance().removeListener(mIDownloadListener);
        }*/
    }

    private void setFilterUpdateOn(GPUImageFilter filter) {
        if (mFilterType == FilterAdapter.Edit_FILTER_TYPE && filter instanceof IDynamicFilter) {
            IDynamicFilter dynamicFilter = (IDynamicFilter) filter;
            dynamicFilter.setUpdateOn(false);
        }
    }

    public void doFilterDataPendingEvent() {
        if (mPendingSortFilterCategoryEvent != null) {
            onSortFilterCategory(mPendingSortFilterCategoryEvent);
            mPendingSortFilterCategoryEvent = null;
        }
        if (mPendingRefreshFilterCategoryEvent != null) {
            refreshFilterCategory(mPendingRefreshFilterCategoryEvent);
            mPendingRefreshFilterCategoryEvent = null;
        }
    }

    private boolean checkApplyalbe(FilterBean bean) {
        return PluginVersionUtil.verifyPluginVersion((Activity) getContext(),
                BaseOnlineManager.STORE_FUNC_TYPE_FILTER,
                bean.getVersionCode());
    }

    public void onSortFilterCategory(final SortFilterCategory event) {
        // 滤镜分类排序后处理
        if (mFilterCategoryAnimationing) {
            mPendingSortFilterCategoryEvent = event;
            return;
        }
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                mFilterCategoryAdapter.setData(DataManager.getInstance().loadAllFilterCategory());
                if (mCurrentFilterBean != null) {
                    int selPosition = mFilterCategoryAdapter.getPositionByCategoryId(mCurrentFilterBean.getCategoryId());
                    mFilterCategoryAdapter.setSelItemIndex(selPosition, null);
                    mFilterCategoryListView.setSelection(selPosition);
                } else {
                    mFilterCategoryAdapter.setSelItemIndex(0, null);
                    mFilterCategoryListView.setSelection(0);
                }
                mFilterCategoryAdapter.notifyDataSetChanged();
            }
        });
    }

    public void onRefreshFilterCategory(final RefreshFilterCategory event) {
        if (mFilterCategoryAnimationing) {
            mPendingRefreshFilterCategoryEvent = event;
            return;
        }
        refreshFilterCategory(event);
    }

    private void refreshFilterCategory(final RefreshFilterCategory event) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                mAllFilterBean = DataManager.getInstance().getLocalFilterListStatusUseByOrder();
                getDownloadedFilters();
                if (!TextUtils.isEmpty(event.delCategoryId)) {
                    // 删除滤镜分类
                    if (mCurrentFilterBean != null && mCurrentFilterBean.getCategoryId().equals(event.delCategoryId)) {
                        // 当前选中滤镜为删除分类，将选中滤镜设为Original
                        mCurrentFilterBean = null;
                        switchFilter(null);
                        mFilterCategoryAdapter.setSelItemIndex(0, null);
                        mFilterCategoryAdapter.notifyDataSetChanged();
                        mFilterCategoryListView.setSelection(0);

                        mFilterAdapter.setData(DataManager.getInstance().loadAllFilter(isFromStash()));
                        mFilterAdapter.setSeletcItemPosition(0);
                        mFilterAdapter.notifyDataSetChanged();
                        mFilterListView.setSelection(0);

                        mActivity.setFilter(mDefaultFilter);
                        mCurrentFilterName = ImageFilterTools.FILTER_NAME_DEFAULT;
                        mActivity.showBottomBar(true, BottomInsideBarView.TYPE_PROGRESS);
                    } else {
                        mFilterAdapter.setData(DataManager.getInstance().loadAllFilter(isFromStash()));
                        mFilterAdapter.notifyDataSetChanged();
                    }
                } else {
                    // 添加滤镜分类
                    if (!TextUtils.isEmpty(event.showCategoryId)) {
                        // 刷新滤镜分类后，如果需要显示指定分类，则打开二级页面
                        int selPosition = mFilterAdapter.getPositionByFilterPkgName(event.showCategoryId);
                        mFilterAdapter.setSeletcItemPosition(selPosition);
                        mFilterAdapter.notifyDataSetChanged();
                        scollToPosition(selPosition, mFilterListView);

                        if (selPosition != 0) {
                            FilterBean filterBean = mFilterAdapter.getData().get(selPosition);
                            switchFilter(filterBean);
                        }

                        mFilterAdapter.setStartAnmitioning(false);
                    } else {
                        //下载之后应用最后下载的滤镜
                        mFilterAdapter.setData(DataManager.getInstance().loadAllFilter(isFromStash()));
                        if (mCheck2ApplyPosition > 0) {
                            FilterBean filterBean = mFilterAdapter.getData().get(mCheck2ApplyPosition);
                            if (switchFilter(filterBean)) {
                                mFilterAdapter.setSeletcItemPosition(mCheck2ApplyPosition);
                                mFilterCategoryAdapter.setSelItemIndex(filterBean.getCategoryPosition(), null);
                                mFilterCategoryAdapter.notifyDataSetChanged();
                                mCheck2ApplyPosition = -1;
                            }
                        }
                        mFilterAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    public void setFilter(FilterBean filter) {
        if (filter != null) {
            mCurrentFilterBean = filter;
            int selPosition = filter.getCategoryPosition();
            mFilterCategoryAdapter.setSelItemIndex(selPosition, null);
            mFilterAdapter.setData(DataManager.getInstance().loadAllFilter(isFromStash()));
            int pos = 0;
            FilterBean bean = null;
            List<FilterBean> data = mFilterAdapter.getData();
            for (int i = 0; i < data.size(); ++i) {
                if (TextUtils.equals(data.get(i).getPackageName(), filter.getPackageName())) {
                    pos = i;
                    bean = data.get(i);
                    break;
                }
            }
            mFilterAdapter.setSeletcItemPosition(pos);
            mFilterAdapter.notifyDataSetChanged();
            switchFilter(bean);
            mFilterAdapter.setStartAnmitioning(false);
        }
    }

    public void switch2NextFilter() {
        FilterBean filterBean = null;
        if (mCurrentFilterBean == null) {
            filterBean = mAllDownloadedBeans.get(0);
        } else {
            int currentIndex = 0;
            for (FilterBean bean : mAllDownloadedBeans) {
                ++currentIndex;
                if (bean.getPackageName().equals(mCurrentFilterBean.getPackageName())) {
                    break;
                }
            }
            if (currentIndex == mAllDownloadedBeans.size()) {
                filterBean = null;
            } else {
                filterBean = mAllDownloadedBeans.get(currentIndex);
            }
        }
        if (filterBean != null && filterBean.getType() == FilterConstant.TYPE_DOWNLOAD) {
            File f = new File(filterBean.getApkUri());
            if (!f.exists()) {
                return;
            }
        }

        boolean result = switchFilter(filterBean);
        if (result) {
            if (mCurrentFilterBean != null) {
                int selPosition = mFilterCategoryAdapter.getPositionByCategoryId(mCurrentFilterBean.getCategoryId());
                mFilterCategoryListView.setSelection(selPosition);
                if (mFilterListView.getVisibility() == VISIBLE) {
                    int pos = mFilterAdapter.getFilterIndex(mCurrentFilterBean.getPackageName());
                    mFilterAdapter.setSeletcItemPosition(pos);
                    mFilterAdapter.notifyDataSetChanged();
                }
            } else {
                mFilterCategoryListView.setSelection(0);
                mFilterCategoryAdapter.setSelItemIndex(0, null);
                mFilterCategoryAdapter.notifyDataSetChanged();
                if (mFilterListView.getVisibility() == VISIBLE) {
                    mFilterAdapter.setSeletcItemPosition(-1);
                    mFilterAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    public void switch2PreFilter() {
        FilterBean filterBean = null;
        if (mCurrentFilterBean == null) {
            filterBean = mAllDownloadedBeans.get(mAllDownloadedBeans.size() - 1);
        } else {
            int currentIndex = 0;
            for (FilterBean bean : mAllDownloadedBeans) {
                if (bean.getPackageName().equals(mCurrentFilterBean.getPackageName())) {
                    break;
                }
                ++currentIndex;
            }
            currentIndex -= 1;
            if (currentIndex < 0) {
                filterBean = null;
            } else {
                filterBean = mAllDownloadedBeans.get(currentIndex);
            }
        }
        if (filterBean != null && filterBean.getType() == FilterConstant.TYPE_DOWNLOAD) {
            File f = new File(filterBean.getApkUri());
            if (!f.exists()) {
                return;
            }
        }

        boolean result = switchFilter(filterBean);
        if (result) {
            if (mCurrentFilterBean != null) {
                int selPosition = mFilterCategoryAdapter.getPositionByCategoryId(mCurrentFilterBean.getCategoryId());
                mFilterCategoryListView.setSelection(selPosition);
                if (mFilterListView.getVisibility() == VISIBLE) {
                    int pos = mFilterAdapter.getFilterIndex(mCurrentFilterBean.getPackageName());
                    mFilterAdapter.setSeletcItemPosition(pos);
                    mFilterAdapter.notifyDataSetChanged();
                }
            } else {
                mFilterCategoryListView.setSelection(0);
                mFilterCategoryAdapter.setSelItemIndex(0, null);
                mFilterCategoryAdapter.notifyDataSetChanged();
                if (mFilterListView.getVisibility() == VISIBLE) {
                    mFilterAdapter.setSeletcItemPosition(-1);
                    mFilterAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    public void updateFilterBarTextUI(boolean eanbleShadow) {
        if (!eanbleShadow) {
            if (mFilterAdapter != null) {
                mFilterAdapter.setTextShadowEnable(false);
                mFilterAdapter.notifyDataSetChanged();
            }
            if (mFilterCategoryAdapter != null) {
                mFilterCategoryAdapter.setTextShadowEnable(false);
                mFilterCategoryAdapter.notifyDataSetChanged();
            }
        } else {
            if (mFilterAdapter != null) {
                mFilterAdapter.setTextShadowEnable(true);
                mFilterAdapter.notifyDataSetChanged();
            }
            if (mFilterCategoryAdapter != null) {
                mFilterCategoryAdapter.setTextShadowEnable(true);
                mFilterCategoryAdapter.notifyDataSetChanged();
            }
        }
    }

    public GPUImageFilter getDefaultFilter() {
        return mDefaultFilter;
    }

    public void setOnFilterSwitchListener(OnFilterSwitchListener listener) {
        mOnFilterSwitchListener = listener;
    }

    public void onChooseArtist() {
        int target = -1;
        for (int i = 0; i <= mFilterCategoryAdapter.getData().size() - 1; i++) {
            FilterCategoryBean categoryBean = mFilterCategoryAdapter.getData().get(i);
            if (TextUtils.equals(categoryBean.getName(), getContext().getString(R.string.image_filter_category_artistic))) {
                target = i;
                break;
            }
        }
        if (target != -1) {
            mItemClickSupport.onItemClick(mFilterCategoryListView.getChildAt(target));
        }
    }

    public void scollToPosition(int position, RecyclerView recyclerView) {
        //拿到当前屏幕可见的第一个position跟最后一个postion
        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        //区分情况
        if (position <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            recyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
//            int left = recyclerView.getChildAt(position - firstItem).getLeft();
            int childCount = recyclerView.getChildCount();
            //判断是否需要偏移
            boolean mNeedOffset = Math.abs(recyclerView.getChildAt(0).getLeft()) != recyclerView.getChildAt(childCount - 1).getLeft()
                    - recyclerView.getChildAt(childCount - 2).getLeft();
            int left;
            if (mNeedOffset) {
                left = (recyclerView.getChildAt(childCount - 1).getLeft() - recyclerView.getChildAt(childCount - 2).getLeft())
                        * (position - firstItem) + recyclerView.getChildAt(0).getLeft();
            } else {
                left = (recyclerView.getChildAt(childCount - 1).getLeft() - recyclerView.getChildAt(childCount - 2).getLeft())
                        * (position - firstItem);
            }
            recyclerView.smoothScrollBy(left, 0);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            int n = position - firstItem;
            if (0 <= n) {
                mNeedScroll = false;
                mFromCategoryClick = true;
                //获取要置顶的项顶部离RecyclerView顶部的距离
                int childCount = recyclerView.getChildCount();
                int left = (recyclerView.getChildAt(childCount - 1).getLeft() -
                        recyclerView.getChildAt(childCount - 2).getLeft()) * n;
                //最后的移动
                recyclerView.smoothScrollBy(left, 0);
            }
        }
    }

    public void setCheck2ApplyPosition(String pkgName) {
        if (mFilterAdapter != null) {
            mCheck2ApplyPosition = mFilterAdapter.getPositionByFilterPkgName(pkgName);
        }
    }

    public FilterRecylerAdapter getFilterAdapter() {
        return mFilterAdapter;
    }

    public void setCategoryTextColor(String color) {
        if (mFilterCategoryAdapter != null) {
            mFilterCategoryAdapter.setTextColor(color);
            mFilterCategoryAdapter.notifyDataSetChanged();
        }
    }

    public interface OnFilterSwitchListener {
        void onSwitch(FilterBean bean);
    }
}
